use std::panic;

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Ident, ItemFn};


#[proc_macro_attribute]
pub fn api_convert(_attr: TokenStream, item: TokenStream) -> TokenStream {

    let input = parse_macro_input!(item as ItemFn);

    let fn_name = &input.sig.ident;
    let fn_inputs = &input.sig.inputs;

    let input_type = match fn_inputs.iter().next() {
        Some(syn::FnArg::Typed(pat_type)) => pat_type.ty.as_ref(),
        _ => panic!("not input type"),
    };

    let fn2 = Ident::new(&format!("{}_handle", fn_name), fn_name.span());
    let expanded = quote! {

        #input
        
        async fn #fn2(frame: Frame) -> Result<Box<[u8]>, AppErr> {
            let req: #input_type = frame.parse_req()?;
            let res = #fn_name(req).await?;
            let vec = serde_cbor::to_vec(&res).conv()?;
            Ok(vec.into_boxed_slice())
        }
    };

    //  eprintln!("{}", expanded);

    TokenStream::from(expanded)
}
